package com.fdb.efp.nls.service.impl;

import com.fdb.basic.framework.core.base.FrameworkService;
import com.fdb.basic.framework.core.constant.MonAlrmLvlEnums;
import com.fdb.basic.framework.core.util.DateTool;
import com.fdb.efp.nls.service.domain.CompensatoryDtlInfoBean;
import com.fdb.efp.nls.service.domain.CompensatoryStleCusDtlRptBean;
import com.fdb.efp.nls.service.domain.TxtFileLoadBean;
import com.fdb.efp.nls.service.domain.dw.DwBaiduRepayPlanBean;
import com.fdb.efp.nls.service.facade.CompensatoryTreatmentService;
import com.fdb.efp.nls.service.util.TxtFileLoadPluginBatch;
import com.fdb.efp.nls.service.facade.AccoutErroTempService;
import com.fdb.efp.nls.service.facade.LoanCompensationStatementServiceV2;
import com.fdb.efp.nls.service.vo.AccoutErroTempVO;
import com.fdb.efp.nls.service.vo.LoanCompensationStatementVo;
import com.fdb.efp.report.service.facade.RptCompensationStatementService;
import com.fdb.efp.report.service.vo.RptCompensationStatementVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 需求编号：【 】<br/>
 * 问题编号：【 】<br/>
 * 开发人员：【肖均辉】<br/>
 * 创建日期：【2019-06-06】<br/>
 * 功能描述：代偿明细、代偿结清客户明细报表处理<br/>
 * @author xiaojunhui<br />
 */
@Service("compensatoryTreatmentService")
public class CompensatoryTreatmentServiceImpl implements CompensatoryTreatmentService, FrameworkService {

    private static Logger logger = LoggerFactory.getLogger(CompensatoryTreatmentServiceImpl.class);

    @Autowired
    private AccoutErroTempService accoutErroTempService;

    @Autowired
    private RptCompensationStatementService rptCompensationStatementService;

    @Autowired
    @Qualifier("loanCompensationStatementServiceV2")
    private LoanCompensationStatementServiceV2 loanCompensationStatementServiceV2;

    private final String compensatoryDtlInfo = "代偿明细信息表";

    private final String compensatoryStleCusDtlRpt = "代偿明细信息表";

    private final int readRow=10000;

    private final int isFirstRead = 2;

    private final String fileCharset = "UTF-8";

    private final String dataSplit = ",";

    @Override
    public Boolean compensatoryDtlInfo(String filePath) {

        long startTime = getStartTime(compensatoryDtlInfo,compensatoryDtlInfo);
        try {
            TxtFileLoadPluginBatch txtFileLoadPlugin = new TxtFileLoadPluginBatch(filePath, dataSplit, fileCharset, isFirstRead, readRow);

            List<TxtFileLoadBean> txtFileLoadList = txtFileLoadPlugin.run(new CompensatoryDtlInfoBean());

            if (txtFileLoadList == null || txtFileLoadList.size() < 1) {
                logger.info(compensatoryDtlInfo+"执行结束，耗时：[" + (System.currentTimeMillis() - startTime) / 1000.0 + "]秒，处理结果[读取文件数据为空或出错]");
                return false;
            }
            saveDtlInfo(txtFileLoadList);
            while (!txtFileLoadList.get(txtFileLoadList.size() - 1).isReadedComplete) {

                txtFileLoadPlugin.setFirstRead(false);

                txtFileLoadList = txtFileLoadPlugin.run(new DwBaiduRepayPlanBean());

                if (txtFileLoadList==null||txtFileLoadList.size() <1) {
                    break;
                }
                saveDtlInfo(txtFileLoadList);
            }
            logger.info(compensatoryDtlInfo+"执行结束，耗时：[" + (System.currentTimeMillis() - startTime) / 1000.0 + "]秒，处理结果[成功]");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            addErrorInfo("loan_compensation_statement", MonAlrmLvlEnums.MonAlrmLvlEnum.SERIOUS.getEnname(),  "同步代偿明细信息表数据出错", "同步代偿明细信息表数据出错，错误信息：" + e.getMessage());
            logger.error(compensatoryDtlInfo+"出错，错误信息：" + e.getMessage());
        }
        logger.info(compensatoryDtlInfo+"执行结束，耗时：[" + (System.currentTimeMillis() - startTime) / 1000.0 + "]秒，处理结果[失败]");
        return false;
    }

    @Override
    public Boolean compensatoryStleCusDtlRpt(String filePath) {

        long startTime = getStartTime(compensatoryStleCusDtlRpt,compensatoryStleCusDtlRpt);

        try {
            TxtFileLoadPluginBatch txtFileLoadPlugin = new TxtFileLoadPluginBatch(filePath, dataSplit, fileCharset, isFirstRead, readRow);

            List<TxtFileLoadBean> txtFileLoadList = txtFileLoadPlugin.run(new CompensatoryStleCusDtlRptBean());

            if (txtFileLoadList == null || txtFileLoadList.size() < 1) {
                logger.info(compensatoryDtlInfo+"执行结束，耗时：[" + (System.currentTimeMillis() - startTime) / 1000.0 + "]秒，处理结果[读取文件数据为空或出错]");
                return false;
            }
            saveStleCusDtlRpt(txtFileLoadList);

            while (!txtFileLoadList.get(txtFileLoadList.size() - 1).isReadedComplete) {

                txtFileLoadPlugin.setFirstRead(false);

                txtFileLoadList = txtFileLoadPlugin.run(new DwBaiduRepayPlanBean());

                if (txtFileLoadList==null||txtFileLoadList.size() <1) {
                    break;
                }
                saveStleCusDtlRpt(txtFileLoadList);
            }
            logger.info(compensatoryDtlInfo+"执行结束，耗时：[" + (System.currentTimeMillis() - startTime) / 1000.0 + "]秒，处理结果[成功]");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            addErrorInfo("rpt_compensation_statement", MonAlrmLvlEnums.MonAlrmLvlEnum.SERIOUS.getEnname(),  "同步代偿明细信息表数据出错", "同步代偿明细信息表数据出错，错误信息：" + e.getMessage());
            logger.error(compensatoryDtlInfo+"出错，错误信息：" + e.getMessage());
        }
        logger.info(compensatoryDtlInfo+"执行结束，耗时：[" + (System.currentTimeMillis() - startTime) / 1000.0 + "]秒，处理结果[失败]");
        return false;
    }

    private long getStartTime(String compensatoryStleCusDtlRp,String info) {
        long startTime = System.currentTimeMillis();
        logger.info(info + DateTool.formatDate(new Date(startTime), DateTool.PATTERN_DATETIME) + "， 处理开始");
        return startTime;
    }

    public void saveStleCusDtlRpt(List<TxtFileLoadBean> txtFileLoadList) throws Exception {

        List<RptCompensationStatementVO> saveList = (List<RptCompensationStatementVO>) beansCopy(txtFileLoadList, RptCompensationStatementVO.class);

        if (saveList == null) {
            return;
        }
        rptCompensationStatementService.insertOrUpdateBatch(saveList);
    }

    public void saveDtlInfo(List<TxtFileLoadBean> txtFileLoadList) throws Exception {

        List<LoanCompensationStatementVo> loanCompensationStatementVoList = (List<LoanCompensationStatementVo>) beansCopy(txtFileLoadList, LoanCompensationStatementVo.class);

        if (loanCompensationStatementVoList == null) {
            return;
        }
        loanCompensationStatementServiceV2.insertOrUpdateBath(loanCompensationStatementVoList);
    }


    private void addErrorInfo(String tableName, String errorType, String errorMsg, String remark) {
        AccoutErroTempVO accoutErroTempVO = new AccoutErroTempVO();
        // 表名
        accoutErroTempVO.setTableName(tableName);
        // 错误级别
        accoutErroTempVO.setErroType(errorType);
        // 错误信息
        accoutErroTempVO.setErroMsg(errorMsg);
        // 备注
        accoutErroTempVO.setRemark(remark);
        // 创建时间
        accoutErroTempVO.setCreateData(DateTool.getCurrentDateTime());
        // 修改时间
        accoutErroTempVO.setLastModifyTime(DateTool.getCurrentDateTime());
        // 记录异常信息
        accoutErroTempService.insert(accoutErroTempVO);
    }
}
